package file

import (
	"os"
	"promsync/progress/path"
)

func CreateFile(filename string) error {
	dir := path.GetCurrentDir()

	filePath := dir + "/" + filename
	_, err := os.Stat(filePath)
	if err == nil {
		return nil
	}
	if os.IsNotExist(err) {
		temp, err := os.Create(filePath)
		defer temp.Close()
		return err
	}
	return nil
}

func ReadFile(file string) (string, error) {
	dir := path.GetCurrentDir()
	file = dir + "/" + file
	dataByte, errRead := os.ReadFile(file)
	if errRead != nil {
		return "", errRead
	}
	data := string(dataByte)
	return data, nil
}

func RemoveFile(filePath string) error {
	dir := path.GetCurrentDir()
	filePath = dir + "/" + filePath

	_, err := os.Stat(filePath)
	if err == nil {
		err = os.Remove(filePath)
		if err != nil {
			return err
		}
		return nil

	}
	return nil

}

func WriteAndCreate(filePath string, content string) error {
	dir := path.GetCurrentDir()
	filePath = dir + "/" + filePath

	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		return err
	}
	_, err = file.Write([]byte(content))
	if err != nil {
		return err
	}
	return file.Close()
}

func WriteAndCreateFullPath(filePath string, content string) error {
	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		return err
	}

	err = file.Truncate(0)
	if err != nil {
		return err
	}

	_, err = file.WriteString(content)
	if err != nil {
		return err
	}
	return file.Close()
}
